package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.admin.Analysis;
import com.tanhua.model.vo.AnalysisSummaryVo;
import com.tanhua.model.admin.Information;
import com.tanhua.model.vo.InformationVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CashboardService {

    @Autowired
    private AnalysisMapper analysisMapper;
    @Autowired
    private LogMapper logMapper;

    public AnalysisSummaryVo findSummary() {
        //new对象 创建一个新的vo
        AnalysisSummaryVo vo = new AnalysisSummaryVo();


        //定时间 对接下来的逻辑做计算
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");//昨天的时间


        /**
         * 累计用户数
         */
        Integer integer = analysisMapper.queryCumulativeUsers();
        vo.setCumulativeUsers(integer);


        /**
         * 过去30天活跃用户数
         */                                     //从解析日期中减去天数
        Integer aLong = analysisMapper.actionEndMonth();
        vo.setActivePassMonth(aLong);


        /**
         * 过去7天活跃用户
         */
        Integer aLongs =analysisMapper.actionEndWeek();
        vo.setActivePassWeek(aLongs);
        /**
         * 操作类型,
         * 0101为登录，0102为注册，
         * 0201为发动态，0202为浏览动态，0203为动态点赞，0204为动态喜欢，0205为评论，0206为动态取消点赞，0207为动态取消喜欢，
         * 0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
         */

        /**
         * 今日新增用户数量
         */
        Integer integer1 = analysisMapper.queryByTypeAndLogTime(today);
        vo.setNewUsersToday(integer1);


        /**
         * 今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
         */
        Integer aLong1 = analysisMapper.queryByTypeAndLogTime(yesterday);
        Integer s = baiFenBi(integer1, aLong1);
        vo.setNewUsersTodayRate(s);
        /**
         * 今日登录次数
         */
        Integer integer2 = analysisMapper.queryByLogTime(today);
        vo.setLoginTimesToday(integer2);


        /**
         * 今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
         */
        Integer integer3 = analysisMapper.queryByLogTime(yesterday);
        Integer bigDecimal = baiFenBi(integer2, integer3);
        vo.setLoginTimesTodayRate(bigDecimal);


        /**
         * 今日活跃用户数量
         */
        Integer integer4 = analysisMapper.queryNumActive(today);
        vo.setActiveUsersToday(integer4);


        /**
         * 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
         */
        Integer activeUsersYesToday = analysisMapper.queryNumActive(yesterday);
        Integer activeUsersTodayRate = baiFenBi(integer4, activeUsersYesToday);
        vo.setActiveUsersTodayRate(activeUsersTodayRate);

        return vo;
    }

    /**
     * 百分比
     * BigDecimal
     * Java在java.math包中提供的API类BigDecimal，用来对超过16位有效位的数进行精确的运算。
     * @param current
     * @param last
     */
    public static Integer baiFenBi(Integer current, Integer last) {
        BigDecimal bigDecimal;
        if (last == 0 || last == null) {
            // 当上一期计数为零时，此时增长为倍数增长
            int i = new BigDecimal((current - last) * 100).intValue();
            return i;

        } else {
            bigDecimal = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last),
                    2, BigDecimal.ROUND_HALF_DOWN);//属于五舍六入不是四舍五入 然后保留两位散伙
        return bigDecimal.intValue();
        }
    }


    // 查询  新增、活跃用户、次日留存率
    public InformationVo findByTime(Long sd, Long ed, Integer type) {

        //将时间转为字符串
        String sTime = new SimpleDateFormat("yyyy-MM-dd").format(sd);
        String eTime = new SimpleDateFormat("yyyy-MM-dd").format(ed);

        // 设定返回值
        InformationVo vos = new InformationVo();

        // 查询今年数据
        List<Information> thisYear = queryInformation(sTime, eTime, type);
        vos.setThisYear(thisYear);


        // 查询去年数据
        String lastSd = new DateTime(sTime).minusYears(1).toString("yyyy-MM-dd");
        String lastEd = new DateTime(eTime).minusYears(1).toString("yyyy-MM-dd");
        List<Information> lastYear = queryInformation(lastSd, lastEd, type);
        vos.setLastYear(lastYear);

        return vos;
    }


    private List<Information>  queryInformation(String sd, String ed, Integer type){
        List<Information> vo = new ArrayList<>();
        // 查询今年`新增 数据
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.le("record_date", ed)
                .ge("record_date", sd);
        List<Analysis> list = analysisMapper.selectList(qw);
        if (!CollUtil.isEmpty(list)) {
            for (Analysis analysis : list) {
                Information information = new Information();
                information.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                //根据查询类型，设置返回的数据点的数量
                switch (type) {//101 新增 102 活跃用户 103 次日留存率
                    case 101:
                        information.setAmount(analysis.getNumRegistered());
                        break;
                    case 102:
                        information.setAmount(analysis.getNumActive());
                        break;
                    case 103:
                        information.setAmount(analysis.getNumRetention1d());
                        break;
                }
                vo.add(information);
            }
        }
        return vo;
    }

}
